package middware

import (
	"gateway/core"
	"golang.org/x/time/rate"
	"sync"
)

type ipLimiter struct {
	limiter *rate.Limiter
}

var (
	ipLimiters = make(map[string]*ipLimiter)
	mu         sync.Mutex
)

func RateLimiter(rps int) core.MiddlewareFunc {
	return func(ctx *core.Context) bool {
		ip := ctx.Request.RemoteAddr
		mu.Lock()
		if _, exists := ipLimiters[ip]; !exists {
			ipLimiters[ip] = &ipLimiter{
				limiter: rate.NewLimiter(rate.Limit(rps), rps*2),
			}
		}
		mu.Unlock()

		if !ipLimiters[ip].limiter.Allow() {
			ctx.JSON(429, map[string]string{"error": "Too Many Requests"})
			return false
		}
		return true
	}
}
